package com.xiaok.mobileredis;


import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;

/**
 * @Classname jedisUtils
 * @Description TODO
 * @Date 2020/9/12 15:18
 * @Created by xiaok
 */
@SpringBootTest
public class jedisUtils {
    private static String ip = "127.0.0.1";
    private static int port  = 6379;
    private static JedisPool pool;

    static{
        pool = new JedisPool(ip,port);
    }
    public static Jedis getJedis(){
        return pool.getResource();
    }

    @Test
    public void testLock(){
        getLock("lockKey","10086",10);
    }
    /**
     *实现分布式锁;
     * @param lockKey
     * @param requestId
     * @param timeout
     * @return
     */
    public static boolean getLock(String lockKey, String requestId, int timeout){
        Jedis jedis = getJedis(); //获取Jedis对象, 用于和远程redis 服务器进行连接
        SetParams setParams = new SetParams();
        setParams.nx(); //设置插入为 setNX 命令
        setParams.ex(timeout); //设置插入的key 包含过期时间
        String result = jedis.set(lockKey, requestId, setParams); //获取成功返回OK ,失败返回 null
        System.out.println(result);
        return result.equals("ok");
    }

    /**
     *
     * @param lockKey
     * @param requestId
     * @param timeout
     * @return
     */
    public static synchronized boolean getLock2(String lockKey, String requestId, int timeout){
        Jedis jedis = getJedis(); //获取Jedis对象, 用于和远程redis 服务器进行连接
        Long result = jedis.setnx(lockKey, requestId); //判断当前的lockKey是否存在,value为requestId
        if( result ==1 ){ //插入成功
            //设置过期时间
            jedis.expire(lockKey,timeout);
            return true;
        }
        return false;
    }

    /**
     * 释放分布式锁
     * @param lockKey
     * @param requestId
     */
    public static void releaseLock(String lockKey,String requestId){
        Jedis jedis = getJedis();
        if (requestId.equals(jedis.get(lockKey))){//释放
            jedis.del(lockKey);
        }
    }
}
